package com.xiaodou.mjf.web.xface.user.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.service.BankCardCashioService;
import com.xiaodou.mjf.application.core.service.BankCardService;
import com.xiaodou.mjf.application.core.service.CardBinsService;
import com.xiaodou.mjf.application.user.manager.MemberManager;
import com.xiaodou.mjf.application.user.service.MemberSecurityService;
import com.xiaodou.mjf.entity.core.BankCardCashio;
import com.xiaodou.mjf.entity.core.CardBins;
import com.xiaodou.mjf.entity.user.MemberSecurity;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.entity.DataEntity;
import com.xiaodou.mjf.infrastructure.common.utils.Encrypt;
import com.xiaodou.mjf.infrastructure.common.utils.Global;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.ResultCode;
import com.xiaodou.mjf.web.xface.user.domain.BankCard;

/**
 * Created by Rocky on 2/27/15.
 */
@RestController
@RequestMapping("v1/user")
public class BankCardController extends ApiController {

	@Resource
	BankCardService bankCardService;
	
	@Resource
	CardBinsService cardBinsService;

	@Resource
	MemberSecurityService memberSecurityService;
	
	@Resource
	BankCardCashioService bankCardCashioService;
	
	@Resource
	MemberManager memberManager;
	

	/**
	 * 银行卡列表查询
	 *
	 * @param 客户编号
	 *  id uid 银行名称 bank_name 银行卡号 card_number
	 *
	 */

	@RequestMapping(value = "my/bank_cards", method = RequestMethod.GET)
	public Map<String, Object> bankCards(@RequestHeader(required = false) String uid) {

		// uid="10001";
		Map<String,Object> result = success();
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		List<BankCard> bankCards = new ArrayList<BankCard>();
		com.xiaodou.mjf.entity.core.BankCard bank = new com.xiaodou.mjf.entity.core.BankCard();
		bank.setMemberId(uid);
		bank.setStatus(com.xiaodou.mjf.entity.core.BankCard.NORMAL);
		String imageServer =  Global.getImgPath();
		// 查询数据库返回信息
		List<com.xiaodou.mjf.entity.core.BankCard> list = bankCardService
				.list(bank);
		for (com.xiaodou.mjf.entity.core.BankCard bankCard : list) {
			BankCard entity = new BankCard(bankCard.getBankName(),
					bankCard.getCardNumber(), imageServer+bankCard.getIcon());
			bankCards.add(entity);
		}
    
		result.put("items", bankCards);
		return result;
	}

	/**
	 * 银行卡添加
	 *
	 * @param 客户编号 id 
	 * @param 银行卡号 card_number 
	 *
	 */
	@RequestMapping(value = "my/bank_cards", method = RequestMethod.POST)
	public Map<String, Object> add(@RequestHeader(required = false) String uid,
			@RequestParam(value = "card_number", required = false) String cardNumber
			) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		if (StringUtils.isBlank(cardNumber)) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		//判断银行卡是否存在,若存在则报错
		com.xiaodou.mjf.entity.core.BankCard entity = bankCardService
				.find(uid, cardNumber, DataEntity.NORMAL);
		if (entity != null) {
			return failure(ResultCode.CARDNO_ALREADY_EXIST);
		}
		// 查询数据库返回信息
		entity = new com.xiaodou.mjf.entity.core.BankCard();		
		// 客户编号
		entity.setMemberId(uid);	
		//银行名称 根据bin_prefixla查询 
		CardBins cardBins=cardBinsService.find(cardNumber.substring(0, 6));
		if(cardBins!=null){
			entity.setBankName(cardBins.getBankName());
			
			//银行url
			entity.setIcon(cardBins.getIcon());
		} else {
			entity.setBankName(com.xiaodou.mjf.entity.core.BankCard.OUTHER_BANK_NAME);
			//银行url
			entity.setIcon(com.xiaodou.mjf.entity.core.BankCard.OUTHER_BANK_ICON);
		}
		//银行卡号
		entity.setCardNumber(cardNumber);
		//状态设置为0 正常
		entity.setStatus(DataEntity.NORMAL);
		//card_cashio 判断 如果卡号不存在则添加记录 edit by David 2015/04/27 start 
		BankCardCashio bankCardCashio = bankCardCashioService.findBycardnumber(uid, cardNumber, BankCardCashio.NORMAL);
		if(bankCardCashio==null){		
			bankCardCashio= new BankCardCashio();
			bankCardCashio.setMemberId(uid);
			bankCardCashio.setBankName(entity.getBankName());
			bankCardCashio.setCardNumber(cardNumber);
			bankCardCashio.setStatus(BankCardCashio.NORMAL);
			bankCardCashio.setCashIn(0D);
			bankCardCashio.setCashOut(0D);
		}
		//edit by David 2015/04/27 end
		try {
			memberManager.bankcardAdd(entity,bankCardCashio);
//			bankCardService.save(entity);
//			bankCardCashioService.save(bankCardCashio);
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.BANKCARD_INSERT_ERROR);
		}
		return success();

	}

	/**
	 * 客户编号 uid 银行名称 bank_name 银行卡号 card_number 交易密码 trade_password
	 */
	@RequestMapping(value = "my/bank_cards", method = RequestMethod.DELETE)
	public Map<String, Object> delete(
			@RequestHeader(required = false) String uid,
			@RequestParam(value = "bank_name", required = false) String bankname,
			@RequestParam(value = "card_number", required = false) String cardNumber,
			@RequestParam(value = "trade_password", required = false) String tradePassword) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		if (StringUtils.isBlank(cardNumber)||StringUtils.isBlank(tradePassword)) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		// member_security 取出trade_password，如果正确则在bank_card表进行删除
		MemberSecurity memberSecurity = memberSecurityService.get(uid);
		if(memberSecurity==null){
			return failure(ResultCode.USER_SECURITY_NOT_EXIST);
		}
		if(memberSecurity.getTradePassword()==null){
			return failure(ResultCode.MISSING_TRADEPASSWORD);
		}
		if (!Encrypt.validatePassword(memberSecurity.getTradePassword(),
				tradePassword)) {
			return failure(ResultCode.INVALID_PASSWORD);
		} else {
			try {
				com.xiaodou.mjf.entity.core.BankCard entity = bankCardService
						.find(uid, cardNumber, DataEntity.NORMAL);
				BankCardCashio bankCardCashio=bankCardCashioService.findBycardnumber(uid, cardNumber, BankCardCashio.NORMAL);
				// 将状态设置为1，表示不可用
				bankCardCashio.setStatus(BankCardCashio.DELETE);
				entity.setStatus(com.xiaodou.mjf.entity.core.BankCard.DELETE);
				memberManager.bankcardDel(entity, bankCardCashio);
//				bankCardService.save(entity);
//				bankCardCashioService.save(bankCardCashio);
			} catch (Exception e) {
				logger.error(e.toString());
				return failure(ResultCode.BANKCARD_DELETE_ERROR);
			}
		}
		return success();
	}
}
